package com.nenude.corejava.ch14;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;


public class ChatSerice {
	public static void main(String[] args) {

		// 设置服务器监听窗口，启动服务器监听
		int port = 8888;
		ServerSocket serverSocket = null;
		Socket socket = null;
		InputStream inputStream = null;
		OutputStream outputStream=null;

		try {
			//1·启动服务器监听
			serverSocket = new ServerSocket(port);
			System.out.println("服务器启动成功，请启用客户端进行连接！");
			
			//2·等待客户端进行连接
			socket = serverSocket.accept();
			System.out.println("客户端动成功！");
			//3·客户端连接后， 打开输入流（准备从客户端读取数据输入）
			inputStream = socket.getInputStream();
			outputStream=socket.getOutputStream();
			
			//4·读取客户端发送过来的数据
			byte[] buffer = new byte[512];
			//等待客户端发送的数据，并接受--有阻塞的作用
			int len = inputStream.read(buffer);

			//5·对数据进行处理
			String string = new String(buffer, 0, len);
			System.out.println(string);
			
			//发送数据到客户端
			//outputStream.write(("reply from service!"+string).getBytes("ISO-8859-1"));
			outputStream.write(("reply from service!").getBytes());

		} catch (IOException e) {

			e.printStackTrace();
		} finally {
					
			//6·关闭输入流
			
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {

					e.printStackTrace();
				}
			}
			
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {

					e.printStackTrace();
				}
			}

			if (socket != null) {
				try {
					socket.close();
				} catch (IOException e) {

					e.printStackTrace();
				}
			}

			if (serverSocket != null) {
				try {
					serverSocket.close();
				} catch (IOException e) {

					e.printStackTrace();
				}
			}
		}

	}

}
